package com.tust.app.controller;

import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.tust.app.domain.FileEntity;
import com.tust.app.service.VideoService;
import com.tust.app.util.FileUploadTool;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Controller
public class VideoController {

    @Resource
    VideoService vs;

    @Autowired
    private VideoService videoService;




    @RequestMapping("/vpage")
    public String vpage(HttpServletRequest request) {
        PageHelper.startPage(1, 3);
        List<FileEntity> videos = videoService.findAll();
        PageInfo<FileEntity> page = new PageInfo<>(videos);
        request.setAttribute("pageInfo", page);
        return "home";
    }

    @RequestMapping("/vpage/{pageNum}")
    public String vpage2(@PathVariable("pageNum") Integer pageNum, HttpServletRequest request) {
        PageHelper.startPage(pageNum, 3);
        List<FileEntity> videos = videoService.findAll();
        PageInfo<FileEntity> page = new PageInfo<>(videos);
        request.setAttribute("pageInfo", page);
        return "home";
    }

    @RequestMapping(value = "/avideo", method = RequestMethod.GET)
    public ModelAndView listVideos(ModelMap map) {
        List<FileEntity> videos = videoService.findAll(); // 获取视频列表
        map.put("videoList", videos);
        return new ModelAndView("admin/video/allVideo", map);
    }




    @RequestMapping(value = "/play/{id}", method = RequestMethod.GET)
    public ModelAndView playVideo(@PathVariable("id") int id, ModelMap map) {
        FileEntity video = videoService.findById(id);
        map.put("video", video);
        return new ModelAndView("admin/video/playVideo", map);
    }

    @RequestMapping(value = "/videoUpload", method = RequestMethod.POST)
    public ModelAndView upload(@RequestParam(value = "file", required = false) MultipartFile multipartFile, HttpServletRequest request, ModelMap map) {
        String message = "";
        FileEntity entity = null;

        try {

            FileUploadTool fileUploadTool = new FileUploadTool();
            entity = fileUploadTool.createFile(multipartFile, request);
            if (entity != null) {
                videoService.saveFile(entity);
                message = "上传成功";
                map.put("entity", entity);
                map.put("result", message);
            } else {
                message = "上传失败";
                map.put("result", message);
            }
        } catch (Exception e) {
            e.printStackTrace();
            message = "上传出现错误";
            map.put("result", message);
        }
        return new ModelAndView("admin/video/upload", map);
    }

    @RequestMapping("/deleteVideoById")
    public String deleteVideoById(Integer id,HttpServletRequest request) {

        FileEntity video = videoService.findById(id);
        if(video!=null){
            videoService.deleteVideoById(id);
        }
        String videoName = video.getTitleAlter();
        String fileName = request.getSession().getServletContext().getRealPath("video")+"/"+videoName+".mp4";
        File file = new File(fileName);
        if(file.exists()){
            file.delete();
        }
        return "redirect:/avideo";
    }


    @GetMapping("/download")
    public void download(@RequestParam("filename") String fileName, HttpServletResponse response) {
        try {
            // 确保文件名正确解码
            fileName = new String(fileName.getBytes("ISO8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 文件保存路径
        String fileSaveRootPath = "D:/maven/tomcat/apache-tomcat-8.5.100/webapps/ROOT/uploadedFiles/";
        // 文件路径
        String fileDir = fileSaveRootPath + File.separator + fileName;
        File file = new File(fileDir);
        if (!file.exists()) {
            System.out.println("下载的文件不存在");
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // 设置响应头，控制浏览器下载该文件
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 读取要下载的文件，保存到文件输入流
        try (FileInputStream in = new FileInputStream(fileDir);
             OutputStream out = response.getOutputStream()) {
            // 创建缓冲区
            byte[] buffer = new byte[1024];
            int len;
            // 循环将输入流中的内容读取到缓冲区当中
            while ((len = in.read(buffer)) > 0) {
                // 输出缓冲区的内容到浏览器，实现文件下载
                out.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
